﻿using System;
using System.Data;
using Newtonsoft.Json.Linq;
using TrinityAPI.Base.Tools;

namespace TrinityAPI.Base.Models
{
    public class DBParameter
    {
        public DBParameter(string parameterName, JToken value)
        {
            var val = value.JsonValueToBaseValue();
            if (val != null && value is JValue)
            {
                this.DataType = this.GetDbType(value.Type);
                this.Value = val;
            }
            else
            {
                this.DataType = DbType.String;
                this.Value = DBNull.Value;
            }
            this.Direction = ParameterDirection.Input;
            this.ParameterName = parameterName;
            this.SourceVersion = DataRowVersion.Current;
        }
        public DBParameter(string parameterName, JTokenType type, object value)
        {
            this.Direction = ParameterDirection.Input;
            this.ParameterName = parameterName;
            this.SourceVersion = DataRowVersion.Current;
            this.DataType = this.GetDbType(type);
            this.Value = value;
        }
        private DbType GetDbType(JTokenType type)
        {
            DbType dbType = DbType.String;

            switch (type)
            {
                case JTokenType.String:
                    dbType = DbType.String;
                    break;
                case JTokenType.Integer:
                    dbType = DbType.Int64;
                    break;
                case JTokenType.Date:
                    dbType = DbType.DateTime;
                    break;
                case JTokenType.Float:
                    dbType = DbType.Decimal;
                    break;
                case JTokenType.Boolean:
                    dbType = DbType.Boolean;
                    break;
                case JTokenType.Guid:
                    dbType = DbType.Guid;
                    break;
            }
            return dbType;
        }
        public ParameterDirection Direction { get; set; }
        public bool IsNullable { get; set; }
        public DbType DataType { get; set; }
        public string ParameterName { get; set; }
        public byte Precision { get; set; }
        public byte Scale { get; set; }
        public int Size { get; set; }
        public string SourceColumn { get; set; }
        public DataRowVersion SourceVersion { get; set; }
        public object Value { get; set; }
    }
}
